package com.ruoyi.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.domain.PaymentRequest;
import com.ruoyi.service.PaymentService;
import com.stripe.Stripe;
import com.stripe.exception.StripeException;
import com.stripe.model.PaymentIntent;
import com.stripe.model.Refund;
import com.stripe.param.PaymentIntentCreateParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Map;


/**
 * 支付相关
 */
@RestController
@RequestMapping("/webapi/pay")
@Slf4j
public class OrderPayController {

    @Autowired
    private PaymentService paymentService;

    @PostMapping(value = "/create")
    public ResponseEntity<?> createOrder(@RequestBody PaymentRequest paymentRequest) throws StripeException {
        log.info("Received payment request: {}", paymentRequest);
        try {
            switch (paymentRequest.getPaymentMethodType().toLowerCase()) {
                case "wechat":
                    break;
                case "alipay":
                    // 处理支付宝支付
                    break;
                case "amazon_pay":
                    // 处理亚马逊支付
                    break;
                case "card":
                    // 处理信用卡支付
                    break;
                case "grabpay":
                    // 处理GrabPay支付
                    break;
                case "paypal":
                    // 处理PayPal支付
                    break;
                case "revolut_pay":
                    // 处理Revolut Pay支付
                    break;
                default:
                    // 处理未知支付方式
                    System.out.println("Unsupported payment method.");
                    break;
            }
            // 调用服务层创建支付意图
            String clientSecret = paymentService.createPaymentIntent(paymentRequest.getCurrency(), paymentRequest.getAmount(),paymentRequest.getPaymentMethodType(), paymentRequest);
            // 返回客户端秘钥
            return ResponseEntity.ok(Collections.singletonMap("clientSecret", clientSecret));
        } catch (Exception e) {
            // 返回错误响应
            return ResponseEntity.badRequest().body(Collections.singletonMap("error", e.getMessage()));
        }

    }

    /**
     * 创建并确认支付意图
     *
     * @param payload 支付请求的 JSON 数据
     * @return 支付意图的客户端秘钥
     */
    @PostMapping("/create-intent")
    public ResponseEntity<?> createPaymentIntent(@RequestBody Map<String, Object> payload) {
        try {
            // 从请求中提取参数
            String currency = (String) payload.get("currency");
            long amount = ((Number) payload.get("amount")).longValue();
            String paymentMethodType = (String) payload.get("paymentMethodType");
            Map<String, Object> paymentDetails = (Map<String, Object>) payload.get("paymentDetails");

            // 提取额外的元数据
            String description = (String) payload.get("description");
            String customerId = (String) payload.get("customerId");
            String orderId = (String) payload.get("orderId");
            String userId = (String) payload.get("userId");
            String orderType = (String) payload.get("orderType");
            String packageId = (String) payload.get("packageId");
            String packageName = (String) payload.get("packageName");
            String clientSecret = paymentService.createAndConfirmPaymentIntent(currency, amount, paymentMethodType, paymentDetails, new PaymentRequest(description, customerId, orderId, userId, orderType, packageId, packageName));

            // 返回客户端秘钥
            return ResponseEntity.ok(Collections.singletonMap("clientSecret", clientSecret));
        } catch (Exception e) {
            // 返回错误响应
            return ResponseEntity.badRequest().body(Collections.singletonMap("error", e.getMessage()));
        }
    }

    /**
     * 发起退款
     *
     * @param paymentIntentId 支付意图的 ID
     * @param amount          退款金额（单位为分），可选
     * @return Refund 对象
     */
    @PostMapping("/refund")
    public Refund refund(@RequestParam String paymentIntentId, @RequestParam(required = false) Long amount) throws StripeException {
        return paymentService.createRefund(paymentIntentId, amount);
    }

    /**
     * Stripe Webhook 回调接口
     */
    @PostMapping("/webhook")
    public String handleStripeWebhook(HttpServletRequest request) {
        return paymentService.handleStripeWebhook(request);
    }

}
